package com.dreem.singleton.type2;

/**
 * @program: DesignParrtern
 * @description: 饿汉式（静态代码块）
 * @author: Peng
 * @create: 2021-01-22  09:45
 **/
public class SingletonTest02 {
    public static void main(String[] args){
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
        System.out.println("instance1的hashcode() = " + instance1.hashCode());
        System.out.println("instance2的hashcode() = " + instance2.hashCode());
    }
}

// 饿汉式（静态代码块）
class Singleton{
    // 1.构造器私有化，外部不能new
    private Singleton(){

    }

    // 2.本类内部创建对象实例
    private static final Singleton instance;

    static{ // 静态代码块中，创建单例对象
        instance = new Singleton();
    }

    // 3.提供公有的静态方法，返回实例对象
    public static Singleton getInstance(){
        return instance;
    }
}
